# -*- coding: utf-8 -*-
import socket
import time
import os
import cv2
import numpy as np
import io
import struct

ip_port = ('0.0.0.0', 8000) # 复用主机所有网卡

class ImageStreaming(object):
    def __init__(server, h):

        client_cnt = 5
        server.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # 对socket的配置重用ip和端口号
        server.server_socket.bind(ip_port)
        server.server_socket.listen(client_cnt)
        print(ip_port,"open")
        client,addr=server.server_socket.accept()
        server.connect = client.makefile('wb')
        server.start()

    def start(server):
        print ("connect ok")
        stream = io.BytesIO()				
        try:
            while True:			
                img_org = cv2.imread('./tcp_server_py/code.png',cv2.IMREAD_GRAYSCALE)	
                thresh, new_img = cv2.threshold(img_org, 60, 255, cv2.THRESH_BINARY)			
                print(new_img)			
                stream.write(new_img)									
                server.connect.write(struct.pack('<L', stream.tell()))
                
                server.connect.flush()							
                stream.seek(0)													
                server.connect.write(stream.read())								
                stream.seek(0)													
                stream.truncate()												
            server.connect.write(struct.pack('<L', 0))							

        except:
            print(" ")
            print("The customer service is disconnected!")
            
        finally:
            cv2.destroyAllWindows()
            print("与客户端断开连接!")
            print(" ")
	

if __name__ == '__main__':
    # host, port
    while True:
        ImageStreaming(ip_port)
        
        
